<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * t
 *
 * @author jianfeng
 */
class BCafePermitCooker extends BAPermitCooker {

    const PermitType_PermitByBillTimeInterval = 'permitByBillTimeInterval';

    /**
     * 
     * @param type $permitData
     */
    public function getUserPermitList($permitData, $user = NULL) {

        $permitList = $this->getPermitList($permitData);

        $userCooker = new BAUserCooker();

        $user = $userCooker->getUserByInfo($user);

        $pList = array();

        if ($permitList != NULL) {

            if ($user instanceof BUser) {
                $userRoles = BRole::findUserRoles($user, NULL, TRUE);
            }

            $isAllowApply = FALSE;
            foreach ($permitList as $id => $permit) {
                $isAllowApply = $this->checkPermitByRole($permit, $user);
                if ($this->isMemberOfPermitType($permit, BAPermitCooker::PermitType_birthPermit)) {
                    $isAllowApply = $this->isBirthPermitValid($permit);
                }
                if ($this->isMemberOfPermitType($permit, self::PermitType_PermitByBillTimeInterval)) {
                    $isAllowApply = $this->checkPermitByBillTimeInterval($permit);
                }
                if ($isAllowApply) {
                    $pList[$id] = $permit;
                }
            }
        }

        return $pList;
    }

    protected function checkPermitByBillTimeInterval($permit, $lastBillTime = NULL) {

        $billCooker = new BAWeBillCooker();

        $userLastBill = $billCooker->getLastUserBill();

        if ($userLastBill != NULL && $userLastBill->getItem('billTime') != NULL) {
            $lastBillTime = $userLastBill->getItem('billTime')->getValue();

            if ($permit != NULL) {
                $permit = $this->getPermit($permit);

                if ($permit->getItem('billTimeInterval') != NULL && $permit->getItem('timeUnit')) {
                    $length = $permit->getItem('billTimeInterval')->getValue();
                    $unit = $permit->getItem('timeUnit')->getValue();
                    if (is_numeric($length) && $length > 1) {
                        $unit.='s';
                    }

                    if ($length != NULL && $unit != NULL) {
                        $dtLastBillTime = new DateTime();
                        $dtLastBillTime->setTimestamp($lastBillTime);
                        $dtLastBillTime->modify('+ ' . $length . ' ' . $unit);
                        //计算出加上交易时间间隔的数据后的时间
                        $tLastBillTime = $dtLastBillTime->getTimestamp();
                        //如果现在已经超过设定的时间间隔，就返回TRUE
                        if ($tLastBillTime < time()) {
                            return TRUE;
                        }
                    }
                }
            }
        }

        return FALSE;
    }

    public function isBillTimeIntervalPermitExpired($permit) {
        $billCooker = new BAWeBillCooker();

        $userLastBill = $billCooker->getLastUserBill();

        if ($userLastBill->getItem('billTime') != NULL) {
            $lastBillTime = $userLastBill->getItem('billTime')->getValue();

            if ($permit != NULL) {
                $permit = $this->getPermit($permit);

                if ($permit->getItem('billTimeInterval') != NULL && $permit->getItem('timeUnit')) {
                    $length = $permit->getItem('billTimeInterval')->getValue();
                    $unit = $permit->getItem('timeUnit')->getValue();
                    if (is_numeric($length) && $length > 1) {
                        $unit.='s';
                    }

                    if ($length != NULL && $unit != NULL) {
                        $dtLastBillTime = new DateTime();
                        $dtLastBillTime->setTimestamp($lastBillTime);
                        $dtLastBillTime->modify('+ ' . $length . ' ' . $unit);
                        //多加一个月作为过期时间，也就是说如果超过2个月没有回访发放消费券，
                        //用户可以在此后的一个月领取，如果没有领取，就过期
                        $dtLastBillTime->modify('+ 1 month');
                        //计算出加上交易时间间隔的数据后的时间
                        $tLastBillTime = $dtLastBillTime->getTimestamp();
                        //如果现在已经超过设定的时间间隔，就返回TRUE
                        if ($tLastBillTime < time()) {
                            return TRUE;
                        }
                    }
                }
            }
        }

        return FALSE;
    }

    public function getPermitExpireTime($permit, $userData = NULL) {

        if ($this->isMemberOfPermitType($permit, self::PermitType_PermitByBillTimeInterval)) {
            $billCooker = new BAWeBillCooker();

            $userLastBill = $billCooker->getLastUserBill();

            if ($userLastBill->getItem('billTime') != NULL) {
                $lastBillTime = $userLastBill->getItem('billTime')->getValue();

                if ($permit != NULL) {
                    $permit = $this->getPermit($permit);

                    if ($permit->getItem('billTimeInterval') != NULL && $permit->getItem('timeUnit')) {
                        $length = $permit->getItem('billTimeInterval')->getValue();
                        $unit = $permit->getItem('timeUnit')->getValue();
                        if (is_numeric($length) && $length > 1) {
                            $unit.='s';
                        }

                        if ($length != NULL && $unit != NULL) {
                            $dtLastBillTime = new DateTime();
                            $dtLastBillTime->setTimestamp($lastBillTime);
                            $dtLastBillTime->modify('+ ' . $length . ' ' . $unit);
                            //多加一个月作为过期时间，也就是说如果超过2个月没有回访发放消费券，
                            //用户可以在此后的一个月领取，如果没有领取，就过期
                            $dtLastBillTime->modify('+ 1 month');
                            //计算出加上交易时间间隔的数据后的时间
                            $tLastBillTime = $dtLastBillTime->getTimestamp();
                            //如果现在已经超过设定的时间间隔，就返回TRUE
                            if ($tLastBillTime > time()) {
                                return $tLastBillTime;
                            }
                        }
                    }
                }
            }

            return FALSE;
        } else {
            return parent::getPermitExpireTime($permit, $userData);
        }
    }

    public function getPermitTypeList($format = 'aliasList') {

        $list = array(
            BAPermitCooker::PermitType_rolePermit => '角色许可',
            BAPermitCooker::PermitType_birthPermit => '生日许可',
            self::PermitType_PermitByBillTimeInterval => '回访激励许可'
        );

        $permitTypeList = parent::getPermitTypeList($format);

        if ($permitTypeList == NULL) {
            foreach ($list as $name => $value) {
                $this->addPermitType($name, $value);
            }
        }

        return $list;
    }

    /**
     * 检查用户是否有某个许可
     * @param type $permit
     */
    public function checkUserPermit($permit, $user = NULL) {

        if (!$user instanceof BUser) {
            $user = Blyn::app()->getCurrentUser();
        }
        $allowPermitList = $user->getCache('allowPermitList');

        if ($permit instanceof BTreeList) {
            $permitId = $permit->getId();
            if ($allowPermitList != NULL && isset($allowPermitList[$permitId])) {
                $oldChangeTime = $allowPermitList[$permitId];
                $lastChangeTimeItem = $permit->getItem('lastChangeTime');
                if ($lastChangeTimeItem != NULL) {
                    $lastChangeTime = $lastChangeTimeItem->getValue();
                    //如果没有更新过，就返回旧的值
                    if ($lastChangeTime == $oldChangeTime) {
                        return TRUE;
                    }
                }
            }
            if ($this->isMemberOfPermitType($permit, parent::PermitType_birthPermit)) {
                $result = $this->isBirthPermitValid($permit, $user);
                if ($result == NULL) {
                    return $result;
                }
            }
            if ($this->isMemberOfPermitType($permit, self::PermitType_PermitByBillTimeInterval)) {
                $result = $this->checkPermitByBillTimeInterval($permit);
                if ($result != TRUE) {
                    return $result;
                }
                $isExpired = $this->isBillTimeIntervalPermitExpired($permit);
                if ($isExpired) {
                    return FALSE;
                }
            }
            $result = $this->checkPermitByRole($permit, $user);
            if ($result != TRUE) {
                return $result;
            }

            if ($user instanceof BUser) {
                if ($permit->getItem('lastChangeTime') != NULL) {//设置最后更新时间，可以判断是否被更新
                    $allowedPermitList[$permit->getId()] = $permit->getItem('lastChangeTime')->getValue();
                } else {
                    $allowedPermitList[$permit->getId()] = $permit->getId();
                }
                $user->setCache('allowPermitList', $allowedPermitList);
                return TRUE;
            }
        }
    }

    /**
     * 
     * @param type $permitData
     * @return array
     */
    public function getAllActiveLongBillIntervalPermit($permitData) {

        $permitList = $permitTable = $this->getPermitList($permitData);
        $userCooker = new BAUserCooker();

        $retPermitList = array();

        foreach ($permitList as $id => $permit) {
            if ($this->isMemberOfPermitType($permit, self::PermitType_PermitByBillTimeInterval)) {
                $billTimeInterval = 30;
                $billTimeIntervalItem = $permit->getItem('billTimeInterval');
                if ($billTimeIntervalItem != NULL) {
                    $billTimeInterval = $billTimeIntervalItem->getValue();
                }
                $timeUnit = $permit->getItem('timeUnit')->getValue();
                if ($billTimeInterval > 1) {
                    $timeUnit .= 's';
                }
                $users = $this->getAllUserWithLongBillTimeInterval($billTimeInterval . ' ' . $timeUnit);
                foreach ($users as $uId => $userInfo) {
                    $userIdItem = $userInfo->getItem('userId');
                    if ($userIdItem != NULL) {
                        //$isAllowApply = $this->checkPermitByRole($permit, $userInfo);
                        $userId = $userIdItem->getValue();
                        if (is_numeric($userId) && $userId > 0) {
                            $user = new BUser($userId);
                            if ($this->checkPermitByRole($permit, $user)) {
                                array_push($retPermitList, array('userInfo' => $userInfo, 'permit' => $permit));
                            }
                        }
                    }
                }
            }
        }

        return $retPermitList;
    }

    public function getAllUserWithLongBillTimeInterval($timeSpan) {

        $billCooker = new BCafeBillCooker();
        $billTable = $billCooker->getBillTable(BAWeBillCooker::BillType_All_Type);

        $startTime = strtotime('- ' . $timeSpan);
        //计算出整数的时间值
        $timeSpan = time() - $startTime;

        /**
         * 先找到大于时间间隔的用户
         */
        $mobileList = $billTable->getValueList('mobile', array('itemData' => array(
                'billTime' => '>' . $timeSpan)
        ));

        $userCooker = new BAUserCooker();
        $userInfoList = array();
        foreach ($mobileList as $mobile => $count) {
            $userInfo = $userCooker->getUserInfo(array('mobile' => $mobile));
            $userInfoList[$userInfo->getId()] = $userInfo;
        }
        return $userInfoList;
    }

}
